package ru.osu.acm.testing.beans;

import ru.osu.acm.common.entities.Group;
import ru.osu.acm.common.entities.Person;
import ru.osu.acm.common.config.Config;
import ru.osu.acm.testing.Utils;

import javax.annotation.Resource;
import javax.faces.model.SelectItem;
import javax.faces.context.FacesContext;
import javax.faces.component.UIComponent;
import javax.faces.application.FacesMessage;
import javax.faces.validator.ValidatorException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * User: Integra
 * Date: 10.07.2009
 * Time: 17:55:34
 */
public class RegisterUserBean {
    @Resource(name = Config.jndi)
    private DataSource source;
    //private int isadmin;

    private ArrayList<Group> allGroups = new ArrayList<Group>();
    private ArrayList<SelectItem> selectGroups = new ArrayList<SelectItem>();
    private int selectedGroup[];

    private ArrayList<Person> persons = new ArrayList<Person>();

    public String addUserToDB() {
        boolean ok = true;
        String login = Utils.getRequestParam("formregisterPerson:login");
        String password = Utils.getRequestParam("formregisterPerson:password");
        String confirmpassword = Utils.getRequestParam("formregisterPerson:confirmpassword");
        //  int groupID=selectedGroup[0];
        String name = Utils.getRequestParam("formregisterPerson:name");
        String surname = Utils.getRequestParam("formregisterPerson:surname");
        persons.clear();
        int id = 1;
        try {
            Connection conn = source.getConnection();
            try {
                PreparedStatement statement = conn.prepareStatement("select * from person order by id");
                ResultSet resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    id = resultSet.getInt("id") + 1;
                    if (resultSet.getString("login").equals(login)) {
                        ok = false;
                        break;
                    }
                }
                resultSet.close();
                statement.close();
                if (ok) {
                    statement = conn.prepareStatement("insert into person(id, login, pass, firstname, secondname, isadmin) values (?, ?, ?, ?, ?, ?)");
                    statement.setInt(1, id);
                    statement.setString(2, login);
                    statement.setString(3, password);
                    statement.setString(4, name);
                    statement.setString(5, surname);
                    statement.setInt(6, 0);
                    statement.executeUpdate();
                    statement.close();
                    statement = conn.prepareStatement("select id from persongroupmember order by id");
                    resultSet = statement.executeQuery();
                    int curId = 1;
                    while (resultSet.next()) {
                        curId = resultSet.getInt("id") + 1;
                    }
                    statement.close();
                    resultSet.close();
                    for (int i = 0; i < selectedGroup.length; i++) {
                        statement = conn.prepareStatement("insert into persongroupmember(id, persongroup, person) values (?,?,?)");
                        statement.setInt(1, curId);
                        statement.setInt(2, selectedGroup[i]);
                        statement.setInt(3, id);
                        curId += 1;
                        statement.executeUpdate();
                        statement.close();
                    }
                }

            }
            finally {
                conn.close();
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        if (ok) {
            return "login";
        } else {
            return "registerPerson";
        }
    }

    public void passValidator(FacesContext context, UIComponent component, Object value) {
        String pass = Utils.getRequestParam("formregisterPerson:password");
        String curpass = value.toString();
        if (curpass.length() < 5) {
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setDetail(Utils.getLocaleMessage("minLengthOfPassword"));
            message.setSummary(Utils.getLocaleMessage("minLengthOfPassword"));
            throw new ValidatorException(message);
        }
        if (!pass.equals(curpass)) {
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setDetail("The password is not equal to confirm password");
            message.setSummary("The password is not equal to confirm password");
            throw new ValidatorException(message);
        }
    }

    public void loginValidator(FacesContext context, UIComponent component, Object value) {

        String detail = Utils.getLocaleMessage("existLogin");
        String summary = Utils.getLocaleMessage("existLogin");
        boolean ok = true;
        if (value == null) return;
        try {
            Connection conn = source.getConnection();
            try {
                PreparedStatement statement = conn.prepareStatement("select * from person order by id");
                ResultSet resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    if (resultSet.getString("login").equals(value.toString())) {
                        ok = false;
                        break;
                    }
                }
                resultSet.close();
                statement.close();
                if (!ok) {
                    FacesMessage message = new FacesMessage();
                    message.setSeverity(FacesMessage.SEVERITY_ERROR);
                    message.setDetail(detail);
                    message.setSummary(summary);
                    throw new ValidatorException(message);
                }

            }
            finally {
                conn.close();
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public Integer getGroupsCount() {
        getGroups();
        return allGroups.size() - 1;
    }

    public void setGroupsCount() {
    }

    public void getGroups() {
        allGroups = loadGroups();
        if (allGroups.size() > 0) {
            // selectedGroup = allGroups.get(0).getId();
        }
        selectGroups.clear();
        for (Group g : allGroups) {
            if (g.getId() != 4)
                selectGroups.add(new SelectItem(g.getId(), g.getName()));
        }
    }


    public ArrayList<Group> loadGroups() {
        ArrayList<Group> gp = new ArrayList<Group>();
        try {
            Connection conn = source.getConnection();
            try {
                PreparedStatement statement = conn.prepareStatement("select persongroup.id, persongroup.groupname from persongroup order by id");
                ResultSet resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    gp.add(new Group(
                            resultSet.getInt(1),
                            resultSet.getString(2).trim()
                    ));
                }
                resultSet.close();
                statement.close();
            }
            finally {
                conn.close();
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        return gp;
    }

    public ArrayList<SelectItem> getSelectGroups() {
        getGroups();
        return selectGroups;
    }

    public void setSelectGroups(ArrayList<SelectItem> selectgroups) {
        this.selectGroups = selectgroups;
    }

    public int[] getSelectedGroup() {
        return selectedGroup;
    }

    public void setSelectedGroup(int[] selectedgroups) {
        this.selectedGroup = selectedgroups;
    }
}
